package com.slipper.bpmn.dealer.support;

import com.slipper.constants.FlowConstants;
import com.slipper.system.flow.service.FlowInstNodeService;
import com.slipper.system.flow.service.FlowInstService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import com.slipper.bpmn.vo.BpmnVO;
import com.slipper.system.flow.bo.FlowInstBO;
import com.slipper.system.flow.bo.FlowInstNodeBO;
import com.slipper.system.flow.bo.FlowNodeBO;
import com.slipper.bpmn.dealer.INodeDealer;

/**
 * 结束节点处理器
 */
@Component
public class EndNodeDealer implements INodeDealer {
    @Resource
    private FlowInstService flowInstService;
    @Resource
    private FlowInstNodeService flowInstNodeService;

    @Override
    public String[] getTypes() {
        return new String[] { "99" };
    }

    @Override
    public FlowInstNodeBO doDeal(
            int dealCnt,
            boolean finished,
            FlowNodeBO flowNode,
            FlowInstBO flowInst,
            FlowInstNodeBO preInstNode,
            FlowInstNodeBO currInstNode,
            BpmnVO vo) {
        this.checkDealCntAssert(dealCnt);

        FlowInstNodeBO flowInstNodeQO = new FlowInstNodeBO();
        flowInstNodeQO.setInstId(flowInst.getId());
        flowInstNodeQO.setDealStatus(FlowConstants.FlowInstNode.DEAL_STATUS_PENDING);
        if (!this.flowInstNodeService.queryList(flowInstNodeQO).isEmpty()) {
            // 存在实例未处理完成，不进行办结
            return null;
        }

        FlowInstNodeBO flowInstNode = new FlowInstNodeBO();
        flowInstNode.setInstId(flowInst.getId());
        flowInstNode.setPreInstNodeId(preInstNode == null ? null : preInstNode.getId());
        flowInstNode.setLineId(flowNode.getInLineId());
        flowInstNode.setCurrFlowNodeId(flowNode.getId());
        flowInstNode.setStartTime(System.currentTimeMillis());
        flowInstNode.setEndTime(System.currentTimeMillis());
        flowInstNode.setUpdateTime(System.currentTimeMillis());
        flowInstNode.setCreateTime(System.currentTimeMillis());
        flowInstNode.setDealManId(vo.getCurrEmpId());
        flowInstNode.setDealOrgId(vo.getCurrOrgId());
        flowInstNode.setDealStatus(FlowConstants.FlowInstNode.DEAL_STATUS_FINISHED);
        this.flowInstNodeService.save(flowInstNode);

        // 修改实例节点为已处理完成
        FlowInstBO flowInstBO = this.flowInstService.queryBy(flowInst.getId());
        flowInstBO.setDealStatus(FlowConstants.FlowInst.DEAL_STATUS_FINISHED);
        flowInstBO.setEndTime(System.currentTimeMillis());
        this.flowInstService.save(flowInstBO);

        return flowInstNode;
    }
}
